package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

import java.util.LinkedList;
import java.util.List;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/majority-element-ii/">229. 求众数 II</a>
 */
public class Solution229 extends BaseSolution {


    /**
     * 摩尔投票法，一次遍历，时间 O(n)，空间O(1)
     */
    public List<Integer> majorityElement(int[] nums) {
        int v1 = 0, v2 = 0;
        int t1 = 0, t2 = 0;
        for (int v : nums) {
            if (v == v1) {
                t1++;
            } else if (v == v2) {
                t2++;
            } else if (t1 == 0) {
                v1 = v;
                t1 = 1;
            } else if (t2 == 0) {
                v2 = v;
                t2 = 1;
            } else {
                t1--;
                t2--;
            }
        }
        t1 = t2 = 0;
        for (int v : nums) {
            if (v == v1) {
                t1++;
            } else if (v == v2) {
                t2++;
            }
        }
        List<Integer> rst = new LinkedList<>();
        if (t1 > nums.length / 3) {
            rst.add(v1);
        }
        if (t2 > nums.length / 3) {
            rst.add(v2);
        }
        return rst;
    }

    /*
    Hash 方法，需要额外空间，时间 O(n)，空间 O(n)
    public List<Integer> majorityElement(int[] nums) {
        Map<Integer, Integer> map = new TreeMap<>();
        for (int v : nums) {
            map.put(v, map.getOrDefault(v, 0) + 1);
        }
        List<Integer> list = new LinkedList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > nums.length / 3) {
                list.add(entry.getKey());
            }
        }
        return list;
    }
     */

    public static void main(String[] args) {
        Solution229 solution = new Solution229();
        printVals(solution.majorityElement(new int[] {
                1, 2
        }));
    }
}